import { controller, action, routeData } from "maishu-node-mvc";
import { connection } from "../database";
import { Connection } from "typeorm";
import { errors } from "../errors";
import { DataObject } from "../entities";
import { currentAppId } from "../common";

@controller("data-object")
export class DataObjectController {
    @action()
    async get(@connection conn: Connection, @routeData { key }, @currentAppId appId) {
        if (!key) throw errors.routeDataFieldNull("key");
        if (!appId) throw errors.argumentNull("appId");

        let id = `${appId}-${key}`;
        let dataObject = await conn.getRepository(DataObject).findOne(id);
        if (dataObject)
            return dataObject.data;

        return null;
    }

    @action()
    async save(@connection conn: Connection, @routeData { key, data }, @currentAppId appId) {
        if (!key) throw errors.routeDataFieldNull("key");
        if (!data) throw errors.routeDataFieldNull("data");
        let id = `${appId}-${key}`;
        let dataObject = await conn.getRepository(DataObject).findOne(id);
        if (dataObject == null) {
            dataObject = { id, data, applicationId: appId, createDateTime: new Date(Date.now()) };
            await conn.getRepository(DataObject).insert(dataObject);
        }
        else {
            await conn.getRepository(DataObject).update(id, { data });
        }
        return {};
    }

}